package org.openFreely.config;

import io.netty.channel.ChannelInitializer;
import org.openFreely.exception.IllegalPortException;
import org.openFreely.exception.IllegalThreadCountsException;
import org.openFreely.starter.Starter;
import org.openFreely.utils.ServerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class ServerConfig implements ApplicationRunner{

    @Autowired
    private Starter starter;

    @Value("${netty.server.port:9999}")
    private int port;
    @Value("${netty.server.threads:1}")
    private int threadCount;
    @Value("${netty.server.messageInfo:从客户端接收到的内容为:}")
    private String messageInfo;
    @Autowired(required=false)
    private ChannelInitializer channelInitializer;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if(port<=0){
            throw new IllegalPortException("非法的端口号!The port is illegal!");
        }
        ServerUtils.setPort(port);
        if(threadCount<=0){
            throw new IllegalThreadCountsException("非法的参数--线程数!The parameter threads is illegal!");
        }
        ServerUtils.setThreadCount(threadCount);
        if(channelInitializer!=null) {
            ServerUtils.setChannelInitializer(channelInitializer);
        }
        ServerUtils.setMessageInfo(messageInfo);
        starter.bootstrap();
    }

}
